package com.xxxx.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //System.out.println("有文件来了");
        //判断是否是多段数据
        if(ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现
            FileItemFactory fileItemFactory=new DiskFileItemFactory();
            //用于解析上传数据的工具类
            ServletFileUpload servletFileUpload=new ServletFileUpload(fileItemFactory);
            //解析数据,得到每一个表单项
            try {
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环判断每一个表单项，是普通类型还是文件上传
                for (FileItem fileItem : list) {
                    if(fileItem.isFormField()){
                        //普通表单项
                        System.out.println("name属性值："+fileItem.getFieldName());
                        System.out.println("value属性值："+fileItem.getString("UTF-8"));//解决乱码问题
                    }
                    else {
                        System.out.println("name属性值："+fileItem.getFieldName());
                        System.out.println("文件名："+fileItem.getName());
                        try {
                            fileItem.write(new File("D:\\"+fileItem.getName()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }

    }
}
